package viper_config

import (
	"fmt"
	"gin-easy/pkg/global"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"time"
)

type Config struct {
	AppDebug bool   `yaml:"AppDebug"`
	Port     string `yaml:"Port"`
	Mysql    Mysql  `yaml:"Mysql"`
	Redis    Redis  `yaml:"Redis"`
	Log      Log    `yaml:"Log"`
	ES       ES     `yaml:"ES"`
}

type Mysql struct {
	Port     int    `yaml:"Port"`
	DateBase string `yaml:"DateBase"`
	Migrate  bool   `yaml:"Migrate"`
	Host     string `yaml:"Host"`
	User     string `yaml:"User"`
	Pwd      string `yaml:"Pwd"`
}

type Redis struct {
	Host string `yaml:"Host"`
	Port int    `yaml:"Port"`
}
type Log struct {
	Level      string `yaml:"level"`
	Filename   string `yaml:"filename"`
	Maxsize    int    `yaml:"maxsize"`
	MaxAge     int    `yaml:"max_age"`
	MaxBackups int    `yaml:"max_backups"`
}

type ES struct {
	Url                 string        `yaml:"url"`
	Sniff               bool          `yaml:"sniff"`
	HealthCheckInterval time.Duration `yaml:"healthCheckInterval"`
	LogPre              string        `yaml:"logPre"`
	Enable              bool          `yaml:"enable"`
}

var Conf = new(Config)

func Setup() {
	yConfig := viper.New()
	yConfig.SetConfigFile(global.BasePath + "/config/config.yaml") // 指定配置文件路径
	err := yConfig.ReadInConfig()
	if err != nil {
		panic(fmt.Errorf("fatal error viper_config file: %w", err))
	}
	// 将读取的配置信息保存至全局变量Conf
	if err := yConfig.Unmarshal(Conf); err != nil {
		panic(fmt.Errorf("unmarshal conf failed, err:%s \n", err))
	}
	// 监控配置文件变化
	yConfig.WatchConfig()
	// 注意！！！配置文件发生变化后要同步到全局变量Conf
	yConfig.OnConfigChange(func(in fsnotify.Event) {
		fmt.Println("配置文件被修改")
		if err := yConfig.Unmarshal(Conf); err != nil {
			panic(fmt.Errorf("unmarshal conf failed, err:%s \n", err))
		}
	})

}
